//
//  HQRetailersViewController.m
//  MobileiOS
//
//  Created by 郝庆松 on 2018/7/8.
//  Copyright © 2018年 PCITC. All rights reserved.
//

#import "HQRetailersViewController.h"
#import "HQShopFiltrateConditionView.h"
#import "HQShopFiltrateView.h"

@interface HQRetailersViewController ()<HQShopFiltrateConditionViewDelegate,HQShopFiltrateViewDelegate>
{
    UIView *_b;
    UIView *_view2;
    HQShopFiltrateConditionView *_v2;
    
    NSDictionary *_dict1;
    NSDictionary *_dict2;
    NSDictionary *_dict3;
    NSDictionary *_dict4;
    NSDictionary *_dict5;
    
    UITextField *_currentTextField;
    
    __weak IBOutlet UIButton *_cjxzItem;
    __weak IBOutlet UIButton *_cpfgItem;
    __weak IBOutlet UIButton *_jgqjItem;
    __weak IBOutlet UIButton *_sxItem;
}
@end

@implementation HQRetailersViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"零售商产品";
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemTitle:@"搜索" withTitleColor:[self colorHexValue:0x647180] withFont:16 withTarget:self withSelector:@selector(searchItem)];
    
    
    // 下拉刷新
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestShopData];
        [_collectionView.mj_header endRefreshing];
    }];
    [_collectionView.mj_header beginRefreshing];
    
    //创建瀑布流布局
    XRWaterfallLayout *waterfall = [XRWaterfallLayout waterFallLayoutWithColumnCount:2];
    
    //或者一次性设置
    [waterfall setColumnSpacing:10 rowSpacing:10 sectionInset:UIEdgeInsetsMake(10, 10, 10, 10)];
    waterfall.delegate = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"HQShopCollCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    _collectionView.collectionViewLayout = waterfall;
}

/**
 搜索按钮
 */
-(void)searchItem{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"输入搜索关键词" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *txtName = [alert textFieldAtIndex:0];
    txtName.placeholder = @"请输入搜索关键词";
    txtName.text = _currentTextField.text;
    alert.tag = 1001;
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag == 1001){
        if (buttonIndex == 1) {
            _currentTextField = [alertView textFieldAtIndex:0];
            [self requestShopData];
        }
    }
}

//根据item的宽度与indexPath计算每一个item的高度
- (CGFloat)waterfallLayout:(XRWaterfallLayout *)waterfallLayout itemHeightForWidth:(CGFloat)itemWidth atIndexPath:(NSIndexPath *)indexPath {
    //根据图片的原始尺寸，及显示宽度，等比例缩放来计算显示高度
    //    XRImage *image =  self.images[indexPath.item];
    
    XRImage *image = [XRImage imageWithImageDic:@{@"img":@"http://img.zcool.cn/community/010f87596f13e6a8012193a363df45.jpg@1280w_1l_2o_100sh.jpg",@"itemIndex":[NSNumber numberWithInteger:indexPath.row]}] ;
    return image.imageH / image.imageW * itemWidth;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HQShopCollCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if([_dataSource[indexPath.row][@"w_img"] hasPrefix:@"http"]){
        [cell.itemImage setImageWithURL:[NSURL URLWithString:_dataSource[indexPath.row][@"w_img"]] placeholderImage:[UIImage imageNamed:@"none_image"]];
    }else{
        cell.itemImage = nil;
    }
    
    if([_dataSource[indexPath.row][@"w_kucun"] integerValue] > 0){
        cell.syslLabel.hidden= NO;
        cell.syslLabel.text= [NSString stringWithFormat:@"  剩余数量 %ld  ",[_dataSource[indexPath.row][@"w_kucun"] integerValue]];
    }else{
        cell.syslLabel.hidden= YES;
    }
    
    cell.itemLabel.text =_dataSource[indexPath.row][@"w_num"];
    
    if([_dataSource[indexPath.row][@"w_kucun"] integerValue] == 0){
        cell.shopItemStatus.image = [UIImage imageNamed:@"Insidetheshop_Alreadysold"];
    }else{
        if([_dataSource[indexPath.row][@"w_ishot"] integerValue] == 2){
            cell.shopItemStatus.image = [UIImage imageNamed:@"Insidetheshop_Promotion"];
        }else{
            cell.shopItemStatus.image = nil;
        }
    }
    return cell;
}

#pragma mark 选中某行触发的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    HQRetailersDetailViewController *shopDetail = [[HQRetailersDetailViewController alloc]init];
    shopDetail.dataInfo = _dataSource[indexPath.row];
    [self.navigationController pushViewController:shopDetail animated:YES];
}

/**
 刷新样式列表数据
 */
-(void)reloadShopData{
    [self requestShopData];
}

/**
 请求店内
 */
-(void)requestShopData{
    _collectionView.backgroundView = nil;
    [self showHudText:@""];
    
    id thz_id = _dict1?_dict1[@"other_id"]:nil;
    id tse_id = _dict2?_dict2[@"tse_id"]:nil;
    id price_dt = _dict3[@"tpe_begpri"]?[NSString stringWithFormat:@"%@-%@",_dict3[@"tpe_begpri"],_dict3[@"tpe_endpri"]]:nil;
    id sortprice = _dict4?_dict4[@"sort"]:nil;
    id online = _dict5?_dict5[@"sort"]:nil;
    
    if(_dict1||_dict2||_dict3||_dict4||_dict5){
        [_sxItem setTitleColor:[self colorHexValue:0x007AFF] forState:UIControlStateNormal];
    }else{
        [_sxItem setTitleColor:[self colorHexValue:0x333333] forState:UIControlStateNormal];
    }
    
    if(_dict1){
        [_cjxzItem setTitleColor:[self colorHexValue:0x007AFF] forState:UIControlStateNormal];
    }else{
        [_cjxzItem setTitleColor:[self colorHexValue:0x333333] forState:UIControlStateNormal];
    }
    
    if(_dict2){
        [_cpfgItem setTitleColor:[self colorHexValue:0x007AFF] forState:UIControlStateNormal];
    }else{
        [_cpfgItem setTitleColor:[self colorHexValue:0x333333] forState:UIControlStateNormal];
    }
    
    if(_dict3){
        [_jgqjItem setTitleColor:[self colorHexValue:0x007AFF] forState:UIControlStateNormal];
    }else{
        [_jgqjItem setTitleColor:[self colorHexValue:0x333333] forState:UIControlStateNormal];
    }
    
    [HQNetWork requetParam:[HQParam worklists:[UserModelManager userID] thz_id:thz_id tse_id:tse_id price_dt:price_dt sortprice:sortprice online:online searchtitle:_currentTextField.text] withMethod:[HQMethod worklists] suc:^(NSDictionary *sucData) {
        [self hiddnHud];
        if([sucData[kStatus]integerValue] == 1){
            _dataSource = [[NSMutableArray alloc]initWithArray:sucData[@"data"]];
            if(_dataSource.count ==0){
                [self addNoneDataCollView:_collectionView withText:@"列表数据为空"];
            }
            [_collectionView reloadData];
        }else{
            [self tostView:sucData[kInfo]];
        }
    } fail:^{
        [self hiddenErrorHud];
    }];
}

/**
 刷新我的样式数据
 */
- (void)reloadMyExcempleData{
    NSLog(@"刷新我的样式数据");
    [self requestShopData];
}


/**
 筛选
 
 @param sender 按钮
 */
- (IBAction)shaiXuanItem:(id)sender {
    [self hidden2];
    [self showHudText:@""];
    [HQNetWork requetParam:[HQParam getsearchdata:[UserModelManager userID]] withMethod:[HQMethod getsearchdata] suc:^(NSDictionary *sucData) {
        [self hiddnHud];
        if([sucData[kStatus] integerValue]== 1){
            NSLog(@"搜索条件返回数据是: %@",sucData);
            
            NSDictionary *dict = sucData[@"data"];
            
            UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
            _view2 = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
            _view2.backgroundColor = [UIColor blackColor];
            _view2.alpha = 0.3;
            [keyWindow addSubview:_view2];
            
            UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidden2)];
            [_view2 addGestureRecognizer:g];
            
            _b = [[UIView alloc]init];
            _b.frame = CGRectMake(50, 0, SCREEN_WIDTH-50, SCREEN_HEIGHT);
            
            HQShopFiltrateView *v = [HQShopFiltrateView loadShopFiltrateView];
            v.delegate = self;
            NSArray *a = @[
                           @{@"itemName":@"厂家选择",@"itemArray":dict[@"fctlists"]},
                           @{@"itemName":@"产品风格",@"itemArray":dict[@"stylelists"]},
                           @{@"itemName":@"价格区间",@"itemArray":dict[@"pricelists"]},
                           @{@"itemName":@"价格排序",@"itemArray":dict[@"sortprice"]},
                           @{@"itemName":@"上架时间",@"itemArray":dict[@"online"]}];
            v.dataSource = [[NSMutableArray alloc]initWithArray:a];
            [v selctDict:_dict1 withDict2:_dict2 withDict3:_dict3 withDict4:_dict4 withDict5:_dict5];
            v.frame = _b.bounds;
            [_b addSubview:v];
            _b.backgroundColor = [UIColor whiteColor];
            [keyWindow addSubview:_b];
        }else{
            [self tostView:sucData[kInfo]];
        }
    } fail:^{
        [self hiddenErrorHud];
    }];
}

-(void)hidden2{
    [_view2 removeFromSuperview];
    [_b removeFromSuperview];
    [_v2 removeFromSuperview];
}

/**
 价格区间
 
 @param sender 按钮
 */
- (IBAction)jiaGeQuJianItem:(id)sender {
    [self hidden2];
    [self showHudText:@""];
    [HQNetWork requetParam:[HQParam getsearchdata:[UserModelManager userID]] withMethod:[HQMethod getsearchdata] suc:^(NSDictionary *sucData) {
        [self hiddnHud];
        if([sucData[kStatus] integerValue]== 1){
            NSDictionary *dict = sucData[@"data"];
            
            _view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, self.view.frame.size.height - 44)];
            _view2.backgroundColor = [UIColor blackColor];
            _view2.alpha = 0.3;
            [self.view addSubview:_view2];
            [self.view bringSubviewToFront:_view2];
            UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidden2)];
            [_view2 addGestureRecognizer:g];
            
            _v2 = [HQShopFiltrateConditionView loadShopFiltrateView];
            NSArray *a = dict[@"pricelists"];
            [_v2 selectDict:_dict3];
            _v2.delegate = self;
            _v2.type = @"pricelists";
            _v2.dataSource = [[NSMutableArray alloc]initWithArray:a];
            _v2.frame = CGRectMake(0, 44, SCREEN_WIDTH, 260);
            [self.view addSubview:_v2];
            [self.view bringSubviewToFront:_v2];
            
        }else{
            [self tostView:sucData[kInfo]];
        }
    } fail:^{
        [self hiddenErrorHud];
    }];
}

/**
 产品风格
 
 @param sender 按钮
 */
- (IBAction)chanPinFengGeItem:(id)sender {
    [self hidden2];
    [self showHudText:@""];
    [HQNetWork requetParam:[HQParam getsearchdata:[UserModelManager userID]] withMethod:[HQMethod getsearchdata] suc:^(NSDictionary *sucData) {
        [self hiddnHud];
        if([sucData[kStatus] integerValue]== 1){
            NSDictionary *dict = sucData[@"data"];
            
            _view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, self.view.frame.size.height - 44)];
            _view2.backgroundColor = [UIColor blackColor];
            _view2.alpha = 0.3;
            [self.view addSubview:_view2];
            [self.view bringSubviewToFront:_view2];
            UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidden2)];
            [_view2 addGestureRecognizer:g];
            
            _v2 = [HQShopFiltrateConditionView loadShopFiltrateView];
            NSArray *a = dict[@"stylelists"];
            _v2.type = @"stylelists";
            [_v2 selectDict:_dict2];
            _v2.delegate = self;
            _v2.dataSource = [[NSMutableArray alloc]initWithArray:a];
            _v2.frame = CGRectMake(0, 44, SCREEN_WIDTH, 260);
            [self.view addSubview:_v2];
            [self.view bringSubviewToFront:_v2];
            
        }else{
            [self tostView:sucData[kInfo]];
        }
    } fail:^{
        [self hiddenErrorHud];
    }];
}

/**
 厂家选择
 
 @param sender 按钮
 */
- (IBAction)changJiaXuanZeItem:(id)sender {
    [self hidden2];
    [self showHudText:@""];
    [HQNetWork requetParam:[HQParam getsearchdata:[UserModelManager userID]] withMethod:[HQMethod getsearchdata] suc:^(NSDictionary *sucData) {
        [self hiddnHud];
        if([sucData[kStatus] integerValue]== 1){
            NSDictionary *dict = sucData[@"data"];
            
            _view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, self.view.frame.size.height - 44)];
            _view2.backgroundColor = [UIColor blackColor];
            _view2.alpha = 0.3;
            [self.view addSubview:_view2];
            [self.view bringSubviewToFront:_view2];
            UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidden2)];
            [_view2 addGestureRecognizer:g];
            
            _v2 = [HQShopFiltrateConditionView loadShopFiltrateView];
            NSArray *a = dict[@"fctlists"];
            [_v2 selectDict:_dict1];
            _v2.type = @"fctlists";
            _v2.delegate = self;
            _v2.dataSource = [[NSMutableArray alloc]initWithArray:a];
            _v2.frame = CGRectMake(0, 44, SCREEN_WIDTH, 260);
            [self.view addSubview:_v2];
            [self.view bringSubviewToFront:_v2];
            
        }else{
            [self tostView:sucData[kInfo]];
        }
    } fail:^{
        [self hiddenErrorHud];
    }];
}

-(void)filterDict:(NSDictionary *)dict withType:(NSString *)type{
    [self hidden2];
    if([type isEqualToString:@"fctlists"]){
        // 厂家
        _dict1 = dict;
    }else if([type isEqualToString:@"stylelists"]){
        // 产品风格
        _dict2 = dict;
    }else if([type isEqualToString:@"pricelists"]){
        // 价格区间
        _dict3 = dict;
    }
    [self requestShopData];
}

-(void)filter2Dict:(NSDictionary *)dict withDict2:(NSDictionary *)dict2 withDict3:(NSDictionary *)dict3 withDict4:(NSDictionary *)dict4 withDict5:(NSDictionary *)dict5{
    _dict1 = dict;
    _dict2 = dict2;
    _dict3 = dict3;
    _dict4 = dict4;
    _dict5 = dict5;
    NSLog(@"%@=%@=%@=%@=%@",dict,dict2,dict3,dict4,dict5);
    [self hidden2];
    [self requestShopData];
}

@end
